#include "pwm_drv.h"

static void GpioInit(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    // GPIOA时钟使能
    RCC_AHBPeriphClk_Enable(RCC_AHB_PERIPH_GPIOA, ENABLE);

    // PA07复用GTIM_CH4
    PA07_AFx_GTIMCH4();

    // PA07 -- GTIM_CH4 PWM输出
    GPIO_InitStructure.Pins = GPIO_PIN_7;
    GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStructure.IT = GPIO_IT_NONE;
    GPIO_Init(CW_GPIOA, &GPIO_InitStructure);
}

static void PwmInit(void)
{
    GTIM_InitTypeDef GTIM_InitStruct;

    // GTIM时钟使能
    RCC_APBPeriphClk_Enable1(RCC_APB1_PERIPH_GTIM, ENABLE);

    GTIM_InitStruct.Mode = GTIM_MODE_TIME; // 定时器模式
    GTIM_InitStruct.OneShotMode = GTIM_COUNT_CONTINUE;
    GTIM_InitStruct.ToggleOutState = DISABLE;
    GTIM_InitStruct.Prescaler = GTIM_PRESCALER_DIV16;
    GTIM_InitStruct.ReloadValue = Period - 1;
    GTIM_TimeBaseInit(&GTIM_InitStruct);

    GTIM_OCInit(GTIM_CHANNEL4, GTIM_OC_OUTPUT_PWM_LOW);
    GTIM_SetCompare4(100);
    GTIM_ITConfig(GTIM_IT_OV, ENABLE);

    GTIM_Cmd(ENABLE);
}

/**
 * @brief  Configure the nested vectored interrupt controller.
 * @param  None
 * @retval None
 */
static void NVIC_Configuration(void)
{
    __disable_irq();
    NVIC_EnableIRQ(GTIM_IRQn);
    __enable_irq();
}

/**
 * @brief PWM硬件初始化
 * @param
 * @return
 */
void PWMDrvInit(void)
{
    GpioInit();
    PwmInit();
    NVIC_Configuration();
}

/**
 * @brief PWM输出占空比
 * @param duty 占空比
 * @return
 */
void PWMOutput(uint16_t duty)
{
    GTIM_SetCompare4(duty);
}
